package com.seednia.module.util.template.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import com.seednia.module.util.template.service.ITemplate;
import com.seednia.module.util.template.service.ITemplateFactory;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * FreeMarker template factory
 * 
 * @author Young Suk Ahn
 *
 */
public class FreeMarkerTemplateFactory implements ITemplateFactory {

	private Configuration provider = null;
	
	@Override
	public void initialize(Properties props) throws IOException {

		this.provider = new Configuration();
		// Specify the data source where the template files come from.
		// Here I set a file directory for it:
		if (props.containsKey(ITemplateFactory.TEMPLATE_LOADER_PATH)) {
			this.provider.setDirectoryForTemplateLoading(
		        new File(props.getProperty(ITemplateFactory.TEMPLATE_LOADER_PATH)));
		}
		if (props.containsKey(ITemplateFactory.TEMPLATE_LOADER_CLASSPATH)) {
			//provider.setClassForTemplateLoading(
			//		(Class)props.get(ITemplateFactory.TEMPLATE_LOADER_CLASSPATH), "/resources");
			this.provider.setClassForTemplateLoading(TemplateDefaultService.class, "/resources");
		}
		//getClass().getR
		// Specify how templates will see the data-model. This is an advanced topic...
		// but just use this:
		this.provider.setObjectWrapper(new DefaultObjectWrapper());  

	}

	@Override
	public ITemplate getTemplate(String name) throws IOException {
		Template fmTemplate = this.provider.getTemplate(name);
		ITemplate retval = new FreeMarkerTemplate(fmTemplate);
		return retval;
	}

}
